<?php
class Mageex_AdvanceSeo_Block_Page_Html_Head extends Mage_Page_Block_Html_Head
{
	public function getCssJsHtml() {
        if ($this->setCanonicalUrl() || empty($this->_data['canonical_url'])) {
            return parent::getCssJsHtml();
        }
        $html = '<link rel="canonical" href="' . $this->_data['canonical_url'] . '" />' . "\n";
        $html .= parent::getCssJsHtml();
        return $html;
    }

    public function setCanonicalUrl() {
        if (!Mage::helper('advanceseo/meta')->isEnableCanonicalUrl()) {
            return;
        }

        $canonicalUrl = null;

        $productActions = array(
            'catalog_product_view',
            'review_product_list',
            'review_product_view',
            'productquestions_show_index',
        );
		
        if (empty($this->_data['canonical_url'])) {
			// ignore pages
            if (in_array($this->getAction()->getFullActionName(), array_filter(preg_split('/\r?\n/', Mage::helper('advanceseo/meta')->getIgnorePages())))) {
                return;
            } elseif (in_array($this->getAction()->getFullActionName(), $productActions)) {
                $useCategories = Mage::getStoreConfigFlag('catalog/seo/product_use_categories');
				
                
				if ($product = Mage::registry('current_product')) {
                    if ($canonicalUrl = $product->getCanonicalUrl()) {
                        $urlRewrite = Mage::getModel('core/url_rewrite')->loadByIdPath($canonicalUrl);
                        $canonicalUrl = Mage::getUrl('') . $urlRewrite->getRequestPath();
                    } else {
                        $productCanonicalUrl = Mage::helper('advanceseo/meta')->getProductCanonnicalUrl();			
                        $collection = Mage::getResourceModel('advanceseo/core_url_rewrite_collection')
                                        ->filterAllByProductId($product->getId(), $productCanonicalUrl)
                                        ->addStoreFilter(Mage::app()->getStore()->getId(), false);
										
                        if ($urlRewrite = $collection->getFirstItem()) {
                            $canonicalUrl = Mage::getUrl('') . $urlRewrite->getRequestPath();
                        }

                        if (!$canonicalUrl) {
                            $canonicalUrl = $product->getProductUrl(false);
                            if (!$canonicalUrl || $productCanonicalUrl == 0) {
                                $product->setDoNotUseCategoryId(!$useCategories);
                                $canonicalUrl = $product->getProductUrl(false);
                            }
                        }
                    }
                }
            } else {
                $url = Mage::helper('core/url')->getCurrentUrl();
                $parsedUrl = parse_url($url);
                extract($parsedUrl);
                $canonicalUrl = $scheme . '://' . $host . (isset($port) && '80' != $port ? ':' . $port : '') . $path;
            }
			
            if ($canonicalUrl) {
               
				if ('/' != substr($canonicalUrl, -1) && !in_array(substr(strrchr($canonicalUrl, '.'), 1), array('rss', 'html', 'htm', 'xml', 'php'))) {
					$canonicalUrl .= '/';
				}
                
            }
			$this->_data['canonical_url'] = $canonicalUrl;
        }
        if (method_exists($this, 'addLinkRel') && !empty($this->_data['canonical_url'])) {
            $this->addLinkRel('canonical', $this->_data['canonical_url']);
            return true;
        }
    }

    public function getRobots() {
        //NOINDEX, FOLLOW for pages without content
		$noindexPatterns = split(',', Mage::helper('advanceseo/meta')->getWithoutContent());
		foreach ($noindexPatterns as $pattern) {
            if (preg_match('/' . $pattern . '/', $this->getAction()->getFullActionName())) {
                $this->_data['robots'] = 'NOINDEX, FOLLOW';
                break;
            }
        }
		
        $noindexPatterns = array_filter(preg_split('/\r?\n/', Mage::helper('advanceseo/meta')->getAdditionalPages()));
		//NOINDEX pages user
        foreach ($noindexPatterns as $pattern) {
            $pattern = str_replace('*', '.*?', $pattern);
            if (preg_match('%' . $pattern . '%', $this->getAction()->getFullActionName()) || preg_match('%' . $pattern . '%', $this->getAction()->getRequest()->getRequestString())) {
                $this->_data['robots'] = 'NOINDEX, FOLLOW';
                break;
            }
        }
        if (empty($this->_data['robots'])) {
            $this->_data['robots'] = 'INDEX, FOLLOW';
        }


        return $this->_data['robots'];
    }
	/**
     * Retrieve title element text (encoded)
     *
     * @return string
     */
    public function getTitle()
    {
		if (empty($this->_data['title'])) {
			if($this->_product = Mage::registry('current_product')) {
				$this->_data['title'] = Mage::helper('advanceseo/data')->getProductTitle($this->_product);
			}
		}
       return preg_replace("/&#?[a-z0-9]+;/i","",htmlspecialchars(html_entity_decode(trim($this->_data['title']), ENT_QUOTES, 'UTF-8')));
    }
	
	/**
     * Retrieve content for description tag
     *
     * @return string
     */
    public function getDescription()
    {
		if (empty($this->_data['description'])) {
			if ($this->_cate = Mage::registry('current_category')) {				
					$name = $this->_cate->getName();
					$this->_data['description'] = $name;
			}
			if($this->_product = Mage::registry('current_product')) {
				$this->_data['description'] = Mage::helper('advanceseo/data')->getProductDesc($this->_product);
			}
		}
		return preg_replace("/&#?[a-z0-9]+;/i","", htmlspecialchars(html_entity_decode(trim($this->_data['description']), ENT_QUOTES, 'UTF-8')));
        
    }
	/**
     * Retrieve content for keyvords tag
     *
     * @return string
     */
    public function getKeywords()
    {
        if ($this->_cate = Mage::registry('current_category')) {
			if($this->_product = Mage::registry('current_product')) {
				$this->_data['keywords'] = Mage::helper('advanceseo/data')->getProductKw($this->_product);
			}else{
				$name = $this->_cate->getName();
				$this->_data['keywords'] = $name;			
			}
        }else{
			if (empty($this->_data['keywords'])) {
				$this->_data['keywords'] = Mage::getStoreConfig('design/head/default_keywords');
			}else{
				if($this->_product = Mage::registry('current_product')) {
					$this->_data['keywords'] = Mage::helper('advanceseo/data')->getProductKw($this->_product);
				}
			}
		}

        return preg_replace("/&#?[a-z0-9]+;/i","", $this->_data['keywords']);
    }
}
?>
